<%@ page language="java" pageEncoding="utf-8"%>
<%@include file="init_logined.jsp" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%
ServletContext sc = session.getServletContext();
String rootPath = sc.getRealPath("/") + "tpl/";
rootPath = rootPath.replace('\\', '/');

String path = params.get("path");
if(path == null) path = "";

path = path.replaceAll("\\.\\.\\/", "");
path = path.replaceAll("\\.\\.", "");

if(path.length() > 0){
	path = "/".equals(path.substring(0, 1)) ? path.substring(1) : path;
}

params.set("path", path);

String savePath = rootPath + path;

//最大文件大小
long maxSize = 100000000;

response.setContentType("text/html; charset=UTF-8");

if(!ServletFileUpload.isMultipartContent(request)){
	out.println(getError("请选择文件。"));
	return;
}
//检查目录
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
	out.println(getError("上传目录不存在。"));
	return;
}
//检查目录写权限
if(!uploadDir.canWrite()){
	out.println(getError("上传目录没有写权限。"));
	return;
}

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
	FileItem item = (FileItem) itr.next();
	String fileName = item.getName();
	
	if (!item.isFormField()) {
		//检查文件大小
		if(item.getSize() > maxSize){
			out.println(getError("上传文件大小超过限制。"));
			return;
		}
		
		//检查扩展名
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		if(",gif,jpg,jpeg,png,bmp,doc,htm,html,txt,".indexOf("," + fileExt + ",") == -1){
			out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许图片和文本格式。"));
			return;
		}
		
		try{
			File uploadedFile = new File(savePath, fileName);
			if(uploadedFile.exists()) uploadedFile.delete();
			
			item.write(uploadedFile);
		}catch(Exception e){
			out.println(getError("上传文件失败。"));
			return;
		}
		
		DbMap json = new DbMap();
		json.put("error", 0);
		json.put("url", "");
		
		out.print(new Gson().toJson(json));
	}
}
%>
<%!
private String getError(String message) {
	DbMap json = new DbMap();
	
	json.put("error", 1);
	json.put("message", message);
	
	return new Gson().toJson(json);
}
%>